import type { AxiosRequestConfig } from "axios";
import requestQueue from "../utils/requestQueue";
import type { ApiResponse } from "./request";

/**
 * 队列化的API服务
 *
 * 将API请求加入队列，在用户登录后按优先级执行
 * 用于处理需要登录但在未登录状态下可能被调用的API
 * @author BelovedLYC
 */
const queuedApi = {
  /**
   * 发送GET请求（队列化）
   * @param url 请求URL
   * @param config 请求配置
   * @param priority 优先级（数字越小优先级越高）
   * @returns Promise<ApiResponse<T>>
   */
  get<T = unknown>(
    url: string,
    config?: AxiosRequestConfig,
    priority: number = 10
  ): Promise<ApiResponse<T>> {
    return new Promise((resolve, reject) => {
      requestQueue.enqueue({
        url,
        method: "get",
        config,
        priority,
        onSuccess: (response: ApiResponse<T>) => resolve(response),
        onError: (error) => reject(error),
      });
    });
  },

  /**
   * 发送POST请求（队列化）
   * @param url 请求URL
   * @param data 请求数据
   * @param config 请求配置
   * @param priority 优先级（数字越小优先级越高）
   * @returns Promise<ApiResponse<T>>
   */
  post<T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
    priority: number = 10
  ): Promise<ApiResponse<T>> {
    return new Promise((resolve, reject) => {
      requestQueue.enqueue({
        url,
        method: "post",
        data,
        config,
        priority,
        onSuccess: (response: ApiResponse<T>) => resolve(response),
        onError: (error) => reject(error),
      });
    });
  },

  /**
   * 发送聊天请求（队列化，带UI更新回调）
   * @param data 聊天请求数据
   * @param onBeforeSend 发送前回调，用于更新UI状态
   * @param priority 优先级
   * @returns Promise<ApiResponse<T>>
   */
  postChat<T = unknown, D = unknown>(
    data?: D,
    onBeforeSend?: () => void,
    priority: number = 2
  ): Promise<ApiResponse<T>> {
    return new Promise((resolve, reject) => {
      // 添加自定义属性存储UI回调
      const requestData = data as Record<string, unknown>;
      if (requestData) {
        requestData._uiCallback = onBeforeSend;
      }

      // 对于聊天请求，我们不走常规的HTTP请求，因为聊天请求需要SSE连接
      // 而是将该请求标记为特殊处理
      requestQueue.enqueue({
        url: "/ai/chat",
        method: "post",
        data: requestData,
        priority,
        _skipActualRequest: true, // 标记不进行实际HTTP请求
        onSuccess: (response: ApiResponse<T>) => {
          // 这个回调函数通常不会被调用，因为我们跳过了实际请求
          // 但为了兼容性保留它
          resolve(response);
        },
        onError: (error) => {
          // 这个错误回调通常不会被调用
          reject(error);
        },
      });
    });
  },

  /**
   * 发送PUT请求（队列化）
   * @param url 请求URL
   * @param data 请求数据
   * @param config 请求配置
   * @param priority 优先级（数字越小优先级越高）
   * @returns Promise<ApiResponse<T>>
   */
  put<T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
    priority: number = 10
  ): Promise<ApiResponse<T>> {
    return new Promise((resolve, reject) => {
      requestQueue.enqueue({
        url,
        method: "put",
        data,
        config,
        priority,
        onSuccess: (response: ApiResponse<T>) => resolve(response),
        onError: (error) => reject(error),
      });
    });
  },

  /**
   * 发送DELETE请求（队列化）
   * @param url 请求URL
   * @param config 请求配置
   * @param priority 优先级（数字越小优先级越高）
   * @returns Promise<ApiResponse<T>>
   */
  delete<T = unknown>(
    url: string,
    config?: AxiosRequestConfig,
    priority: number = 10
  ): Promise<ApiResponse<T>> {
    return new Promise((resolve, reject) => {
      requestQueue.enqueue({
        url,
        method: "delete",
        config,
        priority,
        onSuccess: (response: ApiResponse<T>) => resolve(response),
        onError: (error) => reject(error),
      });
    });
  },
};

export default queuedApi;
